﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FisheryPlatform.Entity;
using FisheryPlatform.DataAccess.Term;
using FisheryPlatform.Entity.Post;

namespace FisheryPlatform.Bussiness.Term
{
    public class TermManager
    {
        public static bool Save(TermEntity termInfo)
        {
            return TermsDB.Save(termInfo);
        }

        /// <summary>
        /// 不区分大小写
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static bool ExistName(long termId, string name, long parentId, TermTaxonomyEnum taxonomy)
        {
            return TermsDB.ExistName(termId, name, parentId, taxonomy);
        }

        public static List<TermEntity> Search(string sqlWhere, int pageIndex, int pageSize, out int pageCount)
        {
            return TermsDB.Search(sqlWhere, pageIndex, pageSize, out pageCount);
        }

        public static bool DeleteByTermId(long termId)
        {
            return TermsDB.DeleteByTermId(termId);
        }

        /// <summary>
        /// 获取文章 Cate
        /// </summary>
        /// <returns></returns>
        public static List<PostTermEntityForAjax> GetPostCateList()
        {
            return GetPostTermBy(TermTaxonomyEnum.Cate);
        }

        /// <summary>
        /// 获取文章 Tag
        /// </summary>
        /// <returns></returns>
        public static List<PostTermEntityForAjax> GetPostTagList()
        {
            return GetPostTermBy(TermTaxonomyEnum.Tag);
        }

        private static List<PostTermEntityForAjax> GetPostTermBy(TermTaxonomyEnum taxonomy)
        {
            #region
            var pageCount = 0;
            List<TermEntity> termList = TermManager.Search(string.Format(" Taxonomy={0}", (int)taxonomy), 0, 0, out pageCount);
            var resultList = new List<PostTermEntityForAjax>();
            RecursiveCateListForAjax(termList, resultList, 0, 0);
            return resultList;
            #endregion
        }

        private static void RecursiveCateListForAjax(List<TermEntity> sourceList, List<PostTermEntityForAjax> list, long parentId, int level)
        {
            #region
            sourceList.ForEach(item =>
            {
                if (item.ParentId == parentId)
                {
                    list.Add(new PostTermEntityForAjax { name = item.Name, id = item.TermId, level = level });
                    RecursiveCateListForAjax(sourceList, list, item.TermId, level + 1);
                }
            });
            #endregion
        }

        public static List<TermEntity> GetListByTermIds(string termIds)
        {
            return TermsDB.GetListByTermIds(termIds);
        }
    }
}
